import { Directive, Injector } from '@angular/core';
import { Subject } from 'rxjs';

import { MessageService } from './message.service';

@Directive()
// tslint:disable-next-line: directive-class-suffix
export class MessageListenersManager {
  // tslint:disable-next-line
  static __messageListeners__: Function[] = [];
  // tslint:disable-next-line
  readonly __messageListenersTakeUntilDestroy$__ = new Subject<void>();

  public messageService: MessageService;

  constructor(protected injector: Injector) {
    this.messageService = this.injector.get(MessageService);

    MessageListenersManager.__messageListeners__.forEach((item: any) => {
      const [ctr, fun] = item;
      if (this instanceof ctr) {
        const index = MessageListenersManager.__messageListeners__.findIndex(a => a === item);
        if (index > -1) {
          // console.log(`${index} matched:, ${key.name}`);
          fun.apply(this);
          // MessageListenersManager.__messageListeners__.splice(index, 1);
        }
      }
    });
  }

  // tslint:disable-next-line
  ngOnDestroy(): void {
    this.__messageListenersTakeUntilDestroy$__.next();
    this.__messageListenersTakeUntilDestroy$__.complete();
  }

  _ngOnDestroy(): void {
    this.__messageListenersTakeUntilDestroy$__.next();
    this.__messageListenersTakeUntilDestroy$__.complete();
  }
}
